﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using Library.HttpTools;

namespace iNotesNotification
{
    public class iNotesXmlHelper : iNotesHelper
    {
        private iNotesMessage _current;
        private string _lastName = null;
        private iNotesMailbox _mailbox;
        private DateTime _latestMessageDate = DateTime.MinValue;
        private int _numMessages = -1;

        public iNotesXmlHelper() { }

        public void Refresh()
        {
            _latestMessageDate = DateTime.MinValue;
            _numMessages = 0;
        }

        public DateTime LatestMessageDate
        {
            get { return _latestMessageDate; }
        }

        public int NumberMessages
        {
            get { return _numMessages; }
        }

        public string HelperID
        {
            get
            {
                return "xml";
            }
        }

        public string MailUri
        {
            get
            {
                iNotesConfig conf = iNotesConfig.Instance;
                return iNotesController.ReplaceUriTags(conf.NotesFileUrl + conf.XmlUrlSuffix, null);
            }
        }

        public void Parse(FileInfo file, iNotesMailbox mbox)
        {
            _mailbox = mbox;
            parse(file);
        }

        public string MailLocalFileName
        {
            get { return "iNotesEmail.xml"; }
        }

        private void parse(FileInfo file)
        {
            _current = null;
            using (XmlTextReader reader = new XmlTextReader(file.OpenRead()))
            {
                Stack<string> elementStack = new Stack<string>();
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        elementStack.Push(reader.Name);
                        string element = elementStack.Peek();
                        switch (element)
                        {
                            case "viewentries":
                                string numRecords = reader.GetAttribute("toplevelentries");
                                if (!int.TryParse(numRecords, out this._numMessages))
                                {
                                    _numMessages = 0;
                                }
                                break;
                            case "viewentry":
                                if (_current != null && _current.Sender.Length > 0)
                                {
                                    _mailbox.Add(_current);
                                }
                                _current = new iNotesMessage();
                                _current.UniqueID = reader.GetAttribute("unid");
                                _current.NoteID = reader.GetAttribute("noteid");
                                break;
                            case "entrydata":
                                //reader.MoveToAttribute("Name");
                                _lastName = reader.GetAttribute("name");
                                break;
                        }
                    }
                    else if (reader.NodeType == XmlNodeType.Text)
                    {
                        if (elementStack.Count > 0)
                        {
                            string element = elementStack.Peek();
                            switch (element)
                            {
                                case "number":
                                    if (_current != null)
                                    {
                                        if (_lastName == "$Importance")
                                        {
                                            string val = reader.Value;
                                            if (val != "0") _current.Priority = val;
                                        }
                                    }
                                    break;
                                case "datetime":
                                    if (_current != null)
                                    {
                                        if (_lastName == "$70")
                                        {
                                            /*
                                            s = s.Insert(4, "/")
                                            s = s.Insert(7, "/")
                                            s = s.Replace("T", " ")
                                            s = s.Replace("Z", "")
                                            s = s.Insert(13, ":")
                                            s = s.Insert(16, ":")*/
                                            string sdate = reader.Value;
                                            sdate = sdate.Remove(15).Replace("T", " ").Insert(13, ":").Insert(11, ":").Insert(6, " ").Insert(4, "/");
                                            DateTime dt;
                                            if (DateTime.TryParse(sdate, out dt))
                                            {
                                                _current.Date = dt;
                                                if (dt > this._latestMessageDate) this._latestMessageDate = dt;
                                            }
                                            else
                                            {
                                                _current.DateString = reader.Value;
                                            }
                                        }
                                    }
                                    break;
                                case "text":
                                    if (_current != null)
                                    {
                                        if (_lastName == "$93")
                                        {
                                            _current.Sender = reader.Value;
                                        }
                                        else if (_lastName == "$73")
                                        {
                                            _current.Subject = reader.Value;
                                        }
                                    }
                                    break;
                            }
                        }

                    }
                    else if (reader.NodeType == XmlNodeType.EndElement)
                    {
                        if (elementStack.Count > 0) elementStack.Pop();
                    }
                }

                if (_current != null && _current.Sender.Length > 0)
                {
                    _mailbox.Add(_current);
                }
                reader.Close();
            }
        }
    }
}
